package mo.tags.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class L15 {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        for (int first = 0; first < n; first++) {
            if (first > 0 && nums[first] == nums[first-1]) {
                continue;
            }
            int third = n-1;
            int target = -nums[first];
            for (int second = first+1; second < n; second++) {
                if (second > first+1 && nums[second] == nums[second-1]) {
                    continue;
                }
                while (second < third && nums[second]+nums[third] > target) {
                    third--;
                }
                if (second == third) {
                    break;
                }
                if (nums[second]+nums[third] == target) {
                    res.add(Arrays.asList(nums[first], nums[second], nums[third]));
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        L15 test = new L15();
        System.out.println(test.threeSum(new int[]{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6}));
    }

}
